import React from 'react'
import { PageLoading } from '@ant-design/pro-layout'
import { Redirect, connect } from 'umi'
import { stringify } from 'querystring'

class SecurityLayout extends React.Component {
  state = {
    isReady: false,
  }

  componentDidMount () {
    this.setState({
      isReady: true,
    })
    const { dispatch } = this.props
    if (dispatch) {
      dispatch({
        type: 'user/fetchCurrent',
      }).then((res = {}) => {
        if (!res.flag) {
          let reg = /\?(\S*)\#*/
          const query = window.location.href.match(reg)
          return dispatch({
            type: 'user/login',
            payload: query ? query[1] : '',
          }).then(() => {
            dispatch({ type: 'user/fetchCurrent'})
            dispatch({ type: 'global/getBaseOptions' })
          })
        }
        dispatch({ type: 'global/getBaseOptions' })
      }).catch(() => {
        let reg = /\?(\S*)\#*/
        const query = window.location.href.match(reg)
        return dispatch({
          type: 'user/login',
          payload: query ? query[1] : '',
        }).then(() => {
          dispatch({ type: 'user/fetchCurrent'})
          dispatch({ type: 'global/getBaseOptions' })
        })
      })
    }
  }

  render () {
    const { isReady } = this.state
    const { children, loading, currentUser } = this.props // You can replace it to your authentication rule (such as check token exists)
    // 你可以把它替换成你自己的登录认证规则（比如判断 token 是否存在）

    const isLogin = currentUser && currentUser.user_name
    const queryString = stringify({
      redirect: window.location.href,
    })

    if ((!isLogin && loading) || !isReady) {
      return <PageLoading/>
    }

    if (!isLogin && window.location.pathname !== '/user/login') {
      //未登录
      const { dispatch } = this.props
      let reg = /\?(\S*)\#*/
      const query = window.location.href.match(reg)
      if (query) {
      } else {
        return <Redirect to={`/user/login?${queryString}`}/>
      }
    }

    return children
  }
}

export default connect(({ user, loading }) => ({
  currentUser: user.currentUser,
  loading: loading.models.user,
}))(SecurityLayout)
